//
//  LLStatusesModel.swift
//  xinlangweibo
//
//  Created by 任玉林 on 16/6/27.
//  Copyright © 2016年 任玉林. All rights reserved.
//

import UIKit 

class LLStatusesModel: NSObject {
    
    /// 微博创建时间
    var created_at: String?
    
    var createdAtStr: String?{
        
        return getWBTimeStr(created_at ?? "")
    }
    /// 微博ID
    var id: Int64 = 0
    /// 微博信息内容
    var text: String?{
        
        didSet{
            
            textAttr = getWeiboAttr(text ?? "" )
        }
    }
    /// 微博来源
    var sourceAttri:NSMutableAttributedString?
    /// 微博来源
    var source: String?{
        
        didSet{
            
            sourceAttri = getSourceStr(source)
        }
    }
    
    ///用户信息
    var user: LLUserInfoModel?
    ///配图数组
    var pic_urls: [LLPictureInfoModel]?
    
    // 微博内容使用的富文本
    var textAttr: NSMutableAttributedString?
    
    // 转发微博
    var retweeted_status:LLStatusesModel?
    //	int	转发数
    var reposts_count:Int = 0{
        didSet{
            repostsStr = getCountString(reposts_count, title: "转发")
        }
    }
    //	int	评论数
    var comments_count:Int = 0{
        didSet{
            commentsStr = getCountString(comments_count, title: "评论")
        }
    }
    //	int	表态数
    var attitudes_count:Int = 0{
        didSet{
            attitudesStr = getCountString(attitudes_count, title: "赞")
        }
    }
    //	int	转发数
    var repostsStr: String?
    //	int	评论数
    var commentsStr: String?
    //	int	表态数
    var attitudesStr: String?
    
    func getCountString(count: Int, title: String) -> String{
        if count <= 0 {
            return title
        }else if count > 0 && count < 10000{
            return "\(count)"
        }else {
            let countF = CGFloat(count / 1000)/10
            var countStr = "\(countF)"
            // containsString --》判断字符串是否包含字符串
            if countStr.containsString(".0"){
                countStr = countStr.stringByReplacingOccurrencesOfString(".0", withString: "")
            }
            
            return "\(countStr)万"
        }
        
    }
    
    init(dict:[String: AnyObject]) {
        
        super.init()
        
        setValuesForKeysWithDictionary(dict)
        
    }
    
    //微博时间方法
    func getWBTimeStr(creatAt: String) -> String {
        //Thu Jun 30 11:21:04 +0800 2016    ---- +0800 时区 z
        let df = NSDateFormatter()
        
        df.dateFormat = "EEE MMM dd HH:mm:ss z yyyy"
        
        //设置地区
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        //微博时间
        let WBDate = df.dateFromString(creatAt)!
        
        //判断是否是今年
        let  isThisYear: Bool = getIsTisYesr(WBDate)
        
        if isThisYear {
            
            //日历类
            let calendar = NSCalendar.currentCalendar()
            
            //是今天
            if calendar.isDateInToday(WBDate) {
                
                //秒数差值
                let s = NSDate().timeIntervalSinceDate(WBDate)
                
                if s < 60 {
                    
                    return "刚刚"
                }else if s >= 60 && s < 60 * 60 {
                    
                    return "\(Int(s/60))分钟前"
                }else {
                    
                    return "\(Int(s/3600))小时前"
                }
                
                //是昨天
            }else if calendar.isDateInYesterday(WBDate){
                
                df.dateFormat = "昨天 HH:mm"
                
                return df.stringFromDate(WBDate)
                
            }else {
                
                df.dateFormat = "MM月dd日 HH:mm"
                
                return df.stringFromDate(WBDate)
                
            }
            
            //不是今年
        }else{
            
            df.dateFormat = "yyyy年MM月dd日 HH:mm"
            
            let resutl = df.stringFromDate(WBDate)
            
            return resutl
        }
        
    }
    
    //是今年
    func  getIsTisYesr(wbDate:NSDate) -> Bool{
        
        let df = NSDateFormatter()
        
        df.dateFormat = "yyyy"
        
        df.locale = NSLocale(localeIdentifier: "en_US")
        
        //当前时间
        let currentTimeStr = df.stringFromDate(NSDate())
        
        //微博时间
        let wbTimeStr = df.stringFromDate(wbDate)
        
        if currentTimeStr == wbTimeStr {
            
            return true
        }else{
            
            return false
        }
    }
    //微博来源
    func getSourceStr(source: String?) -> NSMutableAttributedString{
        guard let s = source where s.containsString("\">") else{
            
            let r = "来自 星星的你"
            return getSoureAttri(r)
        }
        
        let start = s.rangeOfString("\">")!
        
        let end = s.rangeOfString("</a>")!
        
        let resutl = s.substringWithRange(start.endIndex..<end.startIndex)
        
        let r = "来自 \(resutl)"
        
        return getSoureAttri(r)
    }
    
    //富文本
    func getSoureAttri(result:String) -> NSMutableAttributedString{
        
        let attri = NSMutableAttributedString(string: result)
        
        let range = (result as NSString).rangeOfString("来自")
        
        attri.addAttributes([NSForegroundColorAttributeName:ThemeColor], range: range)
        
        return attri
    }
    
    override func setValue(value: AnyObject?, forKey key: String) {
        if key == "user" {
            // 判断可选值是否存在 而且是否能转成字典
            guard let v = value as?[String: AnyObject] else {
               
                return
            }
            // 需要我们程序员手动字典转模型
            let u = LLUserInfoModel(dict: v)
            // 需要程序员自己对该属性赋值
            user = u
        }else if key == "retweeted_status" {
            // 判断可选值是否有值 而且是否可以转成字典
            guard let v = value as?[String: AnyObject] else{
                return
            }
            let s = LLStatusesModel(dict: v)
            // 给转发模型赋值
            retweeted_status = s
            
        }else if key == "pic_urls" {
            
            guard let v = value as? [[String: AnyObject]]else{
                
                return
            }
            
            var tempArray: [LLPictureInfoModel] = [LLPictureInfoModel]()
            
            for dict in v {
                
                let temp = LLPictureInfoModel(dict:dict)
                
                tempArray.append(temp)
            }
            
            pic_urls = tempArray
            
        }else{
            // 如果重写了setValue for Key 我还需要系统帮我们通过kvc字典转模型 需要父类
            super.setValue(value, forKey: key)
        }
    }
    
    override func setValue(value: AnyObject?, forUndefinedKey key: String) {
        
   
    
    }

}

extension LLStatusesModel{
    
    func getWeiboAttr(text: String) -> NSMutableAttributedString{
        
        let resultAttr = NSMutableAttributedString(string: text)
        
        var matchArray: [LLMatchResult] = [LLMatchResult]()
        
        (text as String).enumerateStringsMatchedByRegex("\\[[a-zA-Z0-9\\u4e00-\\u9fa5]+\\]") { (count, string, range, _) -> Void in
            
            let matchRes = LLMatchResult(string: (string.memory as! String), range: range.memory)
            
            matchArray.append(matchRes)
            
            
        }
        // 倒序遍历
        for match in matchArray.reverse() {
            let emoticon = LLEmojiTool.sharedTool.getSearchEmoticon(match.string)
            // 文本附件
            let att = NSTextAttachment()
            let path = emoticon?.path ?? ""
            let png = emoticon?.png ?? ""
            let name = path + png
            // 设置image
            att.image = UIImage(named: name, inBundle: LLEmojiTool.sharedTool.emoticonbundle, compatibleWithTraitCollection: nil)
            // 行高
            let lineHeight = UIFont.systemFontOfSize(15).lineHeight
            // 设置bounds
            att.bounds = CGRect(x: 0, y: -4, width: lineHeight, height: lineHeight)
            
            let attr = NSAttributedString(attachment: att)
            resultAttr.replaceCharactersInRange(match.range, withAttributedString: attr)
        }

        return resultAttr
    }
    
    
}
